#include "object.h"
#include "exception.h"
#include "engine.h"
#include "error.h"
#include "..\physics\physics.h"
#include "..\common\util.h"
#include "..\common\arraylist.hpp"
#include "..\common\types.h"
#include "..\common\format.h"
#include "..\render\d3d.h"
#include "..\render\d3d_mesh.h"
#include "..\physics\actor.h"
#include "..\math\matrix.h"
#include "..\render\interface_types.h"
#include "..\engine\engine.h"
#include "..\common\def.h"
#include "..\render\d3d.h"
#include "..\sound\dsound.h"
#include "..\input\dinput.h"

CD3D9Device* CObject::GetRenderer()
{
	return mp_Renderer;
}

EESound::CDSound9Device* CObject::GetSound()
{
	return mp_Sound;
}

CDInput9Device* CObject::GetInput()
{
	return mp_Input;
}

CPhysics* CObject::GetPhyisics()
{
	return mp_Physics;
}

HRESULT CObject::Create(void)
{
	return S_OK;
}

HRESULT CObject::Release(void)	
{
	HRESULT result = S_OK;
	if(!ISNULL(m_pModel))
	{
		//Render engine does this
		/*if(FAILED(m_pModel->Release()))
			result = E_FAIL;*/
		m_pModel = NULL;
	}

	if(m_pPhysics)
	{
		if(FAILED(m_pPhysics->Release()))
			result = E_FAIL;
		m_pPhysics = NULL;
	}

	return result;
}

CObject::CObject(void)			
{ 
	m_transform = Matrix4f::identity();  
	m_pModel = NULL;
	m_pPhysics = NULL;
	
	mp_Renderer = CEngine::GetInstance()->GetRenderer();
	mp_Sound = CEngine::GetInstance()->GetSound();
	mp_Input = CEngine::GetInstance()->GetInput();
	mp_Physics = CEngine::GetInstance()->GetPhysics();
}

D3DModel* CObject::getModel()
{
	return m_pModel; 
}

void CObject::setPosition(const Vector3f &position)
{
	m_transform.SetTranslation(position); 
	if(m_pPhysics)
		m_pPhysics->SetTransform(m_transform);
}

Vector3f CObject::GetVelocity() {
	return m_velocity;
}

void CObject::setVelocity(const Vector3f &velocity)
{
	m_velocity = velocity;
	
}
bool CObject::isValid()
{
	return true;
}

bool CObject::isManaged()
{
	return true;
}
void CObject::Update(const float dt)
{
	Vector3f dv = (m_velocity * dt);
	if(m_pModel)
	{
		for(unsigned int i = 0; i < m_pModel->getLODCount(); i++)
		{
			D3DModelLOD *pLOD = m_pModel->getLOD(i);
			for(unsigned int j =0; j < pLOD->getMeshCount(); j++)
			{
				D3DMesh* pMesh = pLOD->getMesh(j);
				pMesh->setVelocity(dv);
			}
		}
	}
	m_transform.SetTranslation(m_transform.Translation() + dv);
}

void CObject::SetTransform(const Matrix4f &t)	
{ 
	m_transform = t;  
}

void CObject::Draw(void)
{ 
	if(m_pModel)
	{
		m_pModel->Draw(m_transform, m_velocity); 
	}
}
